package com.four.bmm.filter;


import com.four.bmm.entity.Admin;
import com.four.bmm.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*@WebFilter(filterName = "IsLoginFilter", urlPatterns = "*.jsp")*/
public class IsLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // System.out.println("初始化IsLoginFilter过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        //将servletRequest强转为 HttpservletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        String urlString = request.getRequestURI();
        //判断请求中是否包含back目录，如果包含转入后台判断，否则转入 前台
        if (urlString.contains("back")) {
            Admin loginAdmin = (Admin) session.getAttribute("loginAdmin");
            //如果不为空
            if (loginAdmin != null) {
                chain.doFilter(servletRequest, servletResponse);
                // response.sendRedirect("back/index.jsp");
            } else {
                if (urlString.endsWith("AdminLoginServlet") || urlString.endsWith("back/login.jsp")) {
                    chain.doFilter(servletRequest, servletResponse);
                } else {
                    //如果获取不到管理员信息，代表管理员没有登录，则转向到登录页面
                    request.getRequestDispatcher("login.jsp").forward(request, response);
                    chain.doFilter(servletRequest, servletResponse);
                    // response.sendRedirect("back/login.jsp");
                }
            }
        } else {
            //从session中获取登录用户信息
            User loginuser = (User) session.getAttribute("loginuser");
            //如果不为空
            if (loginuser != null) {
                chain.doFilter(servletRequest, servletResponse);
            } else {
                //请求用户为空时的处理  放过 登录界面  其他界面 的请求的一律拒绝，并返回到登录界面
                if (urlString.endsWith("login.jsp") || urlString.endsWith("LoginServlet") || urlString.endsWith("IsLoginFilter") || urlString.endsWith("AdminLoginServlet")) {
                    chain.doFilter(servletRequest, servletResponse);
                    return;
                } else {
                    request.getRequestDispatcher("login.jsp").forward(request, response);
                    chain.doFilter(servletRequest, servletResponse);
                }

            }

        }

    }

    @Override
    public void destroy() {
        //System.out.println("销毁IsLoginFilter过滤器");

    }
}
